<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 7.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" integrity="sha256-dABdfBfUoC8vJUBOwGVdm8L9qlMWaHTIfXt+7GnZCIo=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/themes/black/pace-theme-flat-top.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/pace.min.js" integrity="sha256-gqd7YTjg/BtfqWSwsJOvndl0Bxc8gFImLEkXQT8+qj0=" crossorigin="anonymous" defer></script>

<script class="next-config" data-name="main" type="application/json">{"hostname":"tryhub.top","root":"/","images":"/images","scheme":"Gemini","darkmode":true,"version":"8.23.0","exturl":false,"sidebar":{"position":"left","width_expanded":320,"width_dual_column":240,"display":"post","padding":18,"offset":12},"hljswrap":true,"copycode":{"enable":true,"style":"mac"},"fold":{"enable":false,"height":500},"bookmark":{"enable":true,"color":"#222","save":"manual"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"duration":200,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.json","localsearch":{"enable":true,"top_n_per_article":1,"unescape":true,"preload":true,"trigger":"auto"}}</script><script src="/js/config.js" defer></script>

    <meta name="description" content="单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中，应用该模式的类一个类只有一个实例。即一个类只有一个对象实例 简介单例模式是设计模式中最简单的形式之一。这一模式的目的是使得类的一个对象成为系统中的唯一实例。要实现这一点，可以从客户端对其进行实例化开始。因此需要用一种只允许生成对象类的唯一实例的机制，“阻止”所有想要生成对象的访问。使用工厂方">
<meta property="og:type" content="article">
<meta property="og:title" content="单例模式 饿汉模式 懒汉模式 示例">
<meta property="og:url" content="https://tryhub.top/2018/04/24/%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F-%E9%A5%BF%E6%B1%89%E6%A8%A1%E5%BC%8F-%E6%87%92%E6%B1%89%E6%A8%A1%E5%BC%8F-%E7%A4%BA%E4%BE%8B/index.html">
<meta property="og:site_name" content="奇姆的博客">
<meta property="og:description" content="单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中，应用该模式的类一个类只有一个实例。即一个类只有一个对象实例 简介单例模式是设计模式中最简单的形式之一。这一模式的目的是使得类的一个对象成为系统中的唯一实例。要实现这一点，可以从客户端对其进行实例化开始。因此需要用一种只允许生成对象类的唯一实例的机制，“阻止”所有想要生成对象的访问。使用工厂方">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2018-04-24T03:31:57.000Z">
<meta property="article:modified_time" content="2023-07-07T07:27:40.669Z">
<meta property="article:author" content="Jaron Chim">
<meta property="article:tag" content="设计模式">
<meta property="article:tag" content="单例模式">
<meta property="article:tag" content="饿汉模式">
<meta property="article:tag" content="懒汉模式">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://tryhub.top/2018/04/24/%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F-%E9%A5%BF%E6%B1%89%E6%A8%A1%E5%BC%8F-%E6%87%92%E6%B1%89%E6%A8%A1%E5%BC%8F-%E7%A4%BA%E4%BE%8B/">


<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://tryhub.top/2018/04/24/%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F-%E9%A5%BF%E6%B1%89%E6%A8%A1%E5%BC%8F-%E6%87%92%E6%B1%89%E6%A8%A1%E5%BC%8F-%E7%A4%BA%E4%BE%8B/","path":"2018/04/24/单例模式-饿汉模式-懒汉模式-示例/","title":"单例模式 饿汉模式 懒汉模式 示例"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>单例模式 饿汉模式 懒汉模式 示例 | 奇姆的博客</title>
  

  <script src="/js/third-party/analytics/baidu-analytics.js" defer></script>
  <script async src="https://hm.baidu.com/hm.js?1ad13b7aff8bfe9206fa7e12d5c4a4f0"></script>







  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous" defer></script>
<script src="/js/utils.js" defer></script><script src="/js/motion.js" defer></script><script src="/js/sidebar.js" defer></script><script src="/js/next-boot.js" defer></script><script src="/js/bookmark.js" defer></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous" defer></script>
<script src="/js/third-party/search/local-search.js" defer></script>





  <script src="/js/third-party/pace.js" defer></script>


  
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>





  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
<link rel="alternate" href="/atom.xml" title="奇姆的博客" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">奇姆的博客</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li><li class="menu-item menu-item-sitemap"><a href="/sitemap.xml" rel="section"><i class="fa fa-sitemap fa-fw"></i>站点地图</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
      <div class="search-header">
        <span class="search-icon">
          <i class="fa fa-search"></i>
        </span>
        <div class="search-input-container">
          <input autocomplete="off" autocapitalize="off" maxlength="80"
                placeholder="搜索..." spellcheck="false"
                type="search" class="search-input">
        </div>
        <span class="popup-btn-close" role="button">
          <i class="fa fa-times-circle"></i>
        </span>
      </div>
      <div class="search-result-container">
        <div class="search-result-icon">
          <i class="fa fa-spinner fa-pulse fa-5x"></i>
        </div>
      </div>
    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F"><span class="nav-number">1.</span> <span class="nav-text">单例模式</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AE%80%E4%BB%8B"><span class="nav-number">1.1.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8A%A8%E6%9C%BA"><span class="nav-number">1.2.</span> <span class="nav-text">动机</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%A6%81%E7%82%B9"><span class="nav-number">1.3.</span> <span class="nav-text">要点</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%A4%BA%E4%BE%8B"><span class="nav-number">2.</span> <span class="nav-text">示例</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#database-properties-%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6"><span class="nav-number">2.1.</span> <span class="nav-text">database.properties 配置文件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ConfigManagerHungry-%E5%B7%A5%E5%85%B7%E7%B1%BB-%E5%8D%95%E4%BE%8B%E9%A5%BF%E6%B1%89%E6%A8%A1%E5%BC%8F"><span class="nav-number">2.2.</span> <span class="nav-text">ConfigManagerHungry 工具类 单例饿汉模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ConfigManagerIdler-%E5%B7%A5%E5%85%B7%E7%B1%BB-%E5%8D%95%E4%BE%8B%E6%87%92%E6%B1%89%E6%A8%A1%E5%BC%8F"><span class="nav-number">2.3.</span> <span class="nav-text">ConfigManagerIdler 工具类 单例懒汉模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ConfigManager-%E5%B7%A5%E5%85%B7%E7%B1%BB-%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F"><span class="nav-number">2.4.</span> <span class="nav-text">ConfigManager 工具类 单例模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Test-%E6%B5%8B%E8%AF%95%E7%B1%BB"><span class="nav-number">2.5.</span> <span class="nav-text">Test 测试类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%8E%A7%E5%88%B6%E5%8F%B0%E8%BE%93%E5%87%BA%E7%BB%93%E6%9E%9C"><span class="nav-number">2.6.</span> <span class="nav-text">控制台输出结果</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%A4%BA%E4%BE%8B%E4%B8%8B%E8%BD%BD"><span class="nav-number">3.</span> <span class="nav-text">示例下载</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Jaron Chim"
      src="/images/jaron.gif">
  <p class="site-author-name" itemprop="name">Jaron Chim</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">76</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">95</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">144</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/admin-Jaron" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;admin-Jaron" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:tryhub@tryhub.top" title="E-Mail → mailto:tryhub@tryhub.top" rel="noopener me"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>

        </div>
      </div>
        <div class="back-to-top animated" role="button" aria-label="返回顶部">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://tryhub.top/2018/04/24/%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F-%E9%A5%BF%E6%B1%89%E6%A8%A1%E5%BC%8F-%E6%87%92%E6%B1%89%E6%A8%A1%E5%BC%8F-%E7%A4%BA%E4%BE%8B/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/jaron.gif">
      <meta itemprop="name" content="Jaron Chim">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="奇姆的博客">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="单例模式 饿汉模式 懒汉模式 示例 | 奇姆的博客">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          单例模式 饿汉模式 懒汉模式 示例
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2018-04-24 11:31:57" itemprop="dateCreated datePublished" datetime="2018-04-24T11:31:57+08:00">2018-04-24</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2023-07-07 15:27:40" itemprop="dateModified" datetime="2023-07-07T15:27:40+08:00">2023-07-07</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" itemprop="url" rel="index"><span itemprop="name">设计模式</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><h1 id="单例模式"><a href="#单例模式" class="headerlink" title="单例模式"></a>单例模式</h1><p>是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中，应用该模式的类一个类只有一个实例。即一个类只有一个对象实例</p>
<h2 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h2><p>单例模式是设计模式中最简单的形式之一。这一模式的目的是使得类的一个对象成为系统中的唯一实例。要实现这一点，可以从客户端对其进行实例化开始。因此需要用一种只允许生成对象类的唯一实例的机制，“阻止”所有想要生成对象的访问。使用工厂方法来限制实例化过程。这个方法应该是静态方法（类方法），因为让类的实例去生成另一个唯一实例毫无意义。</p>
<span id="more"></span>

<h2 id="动机"><a href="#动机" class="headerlink" title="动机"></a>动机</h2><p>对于系统中的某些类来说，只有一个实例很重要，例如，一个系统中可以存在多个打印任务，但是只能有一个正在工作的任务；一个系统只能有一个窗口管理器或文件系统；一个系统只能有一个计时工具或ID(序号)生成器。如在Windows中就只能打开一个任务管理器。如果不使用机制对窗口对象进行唯一化，将弹出多个窗口，如果这些窗口显示的内容完全一致，则是重复对象，浪费内存资源；如果这些窗口显示的内容不一致，则意味着在某一瞬间系统有多个状态，与实际不符，也会给用户带来误解，不知道哪一个才是真实的状态。因此有时确保系统中某个对象的唯一性即一个类只能有一个实例非常重要。 [3]<br>如何保证一个类只有一个实例并且这个实例易于被访问呢？定义一个全局变量可以确保对象随时都可以被访问，但不能防止我们实例化多个对象。一个更好的解决办法是让类自身负责保存它的唯一实例。这个类可以保证没有其他实例被创建，并且它可以提供一个访问该实例的方法。这就是单例模式的模式动机。</p>
<h2 id="要点"><a href="#要点" class="headerlink" title="要点"></a>要点</h2><p>显然单例模式的要点有三个；一是某个类只能有一个实例；二是它必须自行创建这个实例；三是它必须自行向整个系统提供这个实例。</p>
<h1 id="示例"><a href="#示例" class="headerlink" title="示例"></a>示例</h1><p>读取数据库配置文件 只读取一次</p>
<h2 id="database-properties-配置文件"><a href="#database-properties-配置文件" class="headerlink" title="database.properties 配置文件"></a>database.properties 配置文件</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">username=root</span><br><span class="line">password=simon</span><br></pre></td></tr></table></figure>

<h2 id="ConfigManagerHungry-工具类-单例饿汉模式"><a href="#ConfigManagerHungry-工具类-单例饿汉模式" class="headerlink" title="ConfigManagerHungry 工具类 单例饿汉模式"></a>ConfigManagerHungry 工具类 单例饿汉模式</h2><p>类初始化自行实例化,不存在线程不安全。不具备延迟加载特性</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.util;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.io.InputStream;</span><br><span class="line"><span class="keyword">import</span> java.util.Properties;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 单例 饿汉模式</span></span><br><span class="line"><span class="comment"> * 类初始化自行实例化,不存在线程不安全</span></span><br><span class="line"><span class="comment"> * 不具备延迟加载特性</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ConfigManagerHungry</span> &#123;</span><br><span class="line">    <span class="comment">//类加载自行进行初始化操作</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="type">ConfigManagerHungry</span> <span class="variable">configManagerHungry</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ConfigManagerHungry</span>();</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Properties properties;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//私有构造器 读取数据库配置文件</span></span><br><span class="line">    <span class="keyword">private</span> <span class="title function_">ConfigManagerHungry</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;饿汉模式 ConfigManagerHungry ------&gt;&gt;&gt;&gt; 创建&quot;</span>);</span><br><span class="line">        <span class="type">String</span> <span class="variable">configFile</span> <span class="operator">=</span> <span class="string">&quot;database.properties&quot;</span>;</span><br><span class="line">        properties = <span class="keyword">new</span> <span class="title class_">Properties</span>();</span><br><span class="line">        <span class="type">InputStream</span> <span class="variable">is</span> <span class="operator">=</span> ConfigManagerHungry.class.getClassLoader().getResourceAsStream(configFile);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            properties.load(is);</span><br><span class="line">            is.close();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//全局访问点</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> ConfigManagerHungry <span class="title function_">getConfigManagerHungry</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> configManagerHungry;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getValue</span><span class="params">(String key)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> properties.getProperty(key);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="ConfigManagerIdler-工具类-单例懒汉模式"><a href="#ConfigManagerIdler-工具类-单例懒汉模式" class="headerlink" title="ConfigManagerIdler 工具类 单例懒汉模式"></a>ConfigManagerIdler 工具类 单例懒汉模式</h2><p>具备延迟加载特性。线程不安全</p>
<!-- more -->

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.util;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.io.InputStream;</span><br><span class="line"><span class="keyword">import</span> java.util.Properties;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 单例 懒汉模式</span></span><br><span class="line"><span class="comment"> * 具备延迟加载特性</span></span><br><span class="line"><span class="comment"> * 线程不安全</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ConfigManagerIdler</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> ConfigManagerIdler configManagerIdler;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Properties properties;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//私有构造器 读取数据库配置文件</span></span><br><span class="line">    <span class="keyword">private</span> <span class="title function_">ConfigManagerIdler</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">String</span> <span class="variable">configFile</span> <span class="operator">=</span> <span class="string">&quot;database.properties&quot;</span>;</span><br><span class="line">        properties = <span class="keyword">new</span> <span class="title class_">Properties</span>();</span><br><span class="line">        <span class="type">InputStream</span> <span class="variable">is</span> <span class="operator">=</span> ConfigManagerIdler.class.getClassLoader().getResourceAsStream(configFile);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            properties.load(is);</span><br><span class="line">            is.close();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//全局访问点</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> ConfigManagerIdler <span class="title function_">getConfigManagerIdler</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="literal">null</span> == configManagerIdler) &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;懒汉模式 ConfigManagerIdler ------&gt;&gt;&gt;&gt; 创建&quot;</span>);</span><br><span class="line">            configManagerIdler = <span class="keyword">new</span> <span class="title class_">ConfigManagerIdler</span>();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> configManagerIdler;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getValue</span><span class="params">(String key)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> properties.getProperty(key);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="ConfigManager-工具类-单例模式"><a href="#ConfigManager-工具类-单例模式" class="headerlink" title="ConfigManager 工具类 单例模式"></a>ConfigManager 工具类 单例模式</h2><p>结合饿汉模式与懒汉模式的特性。及具有延迟加载特性并线程安全</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.util;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.io.InputStream;</span><br><span class="line"><span class="keyword">import</span> java.util.Properties;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 单例模式</span></span><br><span class="line"><span class="comment"> * 结合饿汉模式与懒汉模式的特性</span></span><br><span class="line"><span class="comment"> * 及具有延迟加载特性并线程安全</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ConfigManager</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> ConfigManager configManager;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Properties properties;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//私有构造器 读取数据库配置文件</span></span><br><span class="line">    <span class="keyword">private</span> <span class="title function_">ConfigManager</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">String</span> <span class="variable">configFile</span> <span class="operator">=</span> <span class="string">&quot;database.properties&quot;</span>;</span><br><span class="line">        properties = <span class="keyword">new</span> <span class="title class_">Properties</span>();</span><br><span class="line">        <span class="type">InputStream</span> <span class="variable">is</span> <span class="operator">=</span> ConfigManager.class.getClassLoader().getResourceAsStream(configFile);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            properties.load(is);</span><br><span class="line">            is.close();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//使用内部静态类</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">class</span> <span class="title class_">ConfigManagerHelper</span> &#123;</span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">ConfigManager</span> <span class="variable">INSTANCE</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ConfigManager</span>();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//全局访问点</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> ConfigManager <span class="title function_">getConfigManager</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="literal">null</span> == configManager) &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;单例模式 ConfigManager ------&gt;&gt;&gt;&gt; 创建&quot;</span>);</span><br><span class="line">            configManager = ConfigManagerHelper.INSTANCE;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> configManager;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">getValue</span><span class="params">(String key)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> properties.getProperty(key);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="Test-测试类"><a href="#Test-测试类" class="headerlink" title="Test 测试类"></a>Test 测试类</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.test;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.util.ConfigManager;</span><br><span class="line"><span class="keyword">import</span> com.util.ConfigManagerHungry;</span><br><span class="line"><span class="keyword">import</span> com.util.ConfigManagerIdler;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Test</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;one  -----------------&quot;</span>);</span><br><span class="line">        System.out.println(getConfigManager());</span><br><span class="line">        System.out.println(getConfigManagerHungry());</span><br><span class="line">        System.out.println(getConfigManagerIdler());</span><br><span class="line">        System.out.println(<span class="string">&quot;two  -----------------&quot;</span>);</span><br><span class="line">        System.out.println(getConfigManager());</span><br><span class="line">        System.out.println(getConfigManagerHungry());</span><br><span class="line">        System.out.println(getConfigManagerIdler());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 单例模式</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String <span class="title function_">getConfigManager</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">StringBuffer</span> <span class="variable">stringBuffer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">StringBuffer</span>();</span><br><span class="line">        stringBuffer.append(<span class="string">&quot;username : &quot;</span> + ConfigManager.getConfigManager().getValue(<span class="string">&quot;username&quot;</span>) + <span class="string">&quot;\n&quot;</span>);</span><br><span class="line">        stringBuffer.append(<span class="string">&quot;password : &quot;</span> + ConfigManager.getConfigManager().getValue(<span class="string">&quot;password&quot;</span>) + <span class="string">&quot;\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> stringBuffer.toString();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 饿汉模式</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String <span class="title function_">getConfigManagerHungry</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">StringBuffer</span> <span class="variable">stringBuffer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">StringBuffer</span>();</span><br><span class="line">        stringBuffer.append(<span class="string">&quot;username : &quot;</span> + ConfigManagerHungry.getConfigManagerHungry().getValue(<span class="string">&quot;username&quot;</span>) + <span class="string">&quot;\n&quot;</span>);</span><br><span class="line">        stringBuffer.append(<span class="string">&quot;password : &quot;</span> + ConfigManagerHungry.getConfigManagerHungry().getValue(<span class="string">&quot;password&quot;</span>) + <span class="string">&quot;\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> stringBuffer.toString();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 懒汉模式</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String <span class="title function_">getConfigManagerIdler</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">StringBuffer</span> <span class="variable">stringBuffer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">StringBuffer</span>();</span><br><span class="line">        stringBuffer.append(<span class="string">&quot;username : &quot;</span> + ConfigManagerIdler.getConfigManagerIdler().getValue(<span class="string">&quot;username&quot;</span>) + <span class="string">&quot;\n&quot;</span>);</span><br><span class="line">        stringBuffer.append(<span class="string">&quot;password : &quot;</span> + ConfigManagerIdler.getConfigManagerIdler().getValue(<span class="string">&quot;password&quot;</span>) + <span class="string">&quot;\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> stringBuffer.toString();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="控制台输出结果"><a href="#控制台输出结果" class="headerlink" title="控制台输出结果"></a>控制台输出结果</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">one  -----------------</span><br><span class="line">单例模式 ConfigManager ------&gt;&gt;&gt;&gt; 创建</span><br><span class="line">username : root</span><br><span class="line">password : simon</span><br><span class="line"></span><br><span class="line">饿汉模式 ConfigManagerHungry ------&gt;&gt;&gt;&gt; 创建</span><br><span class="line">username : root</span><br><span class="line">password : simon</span><br><span class="line"></span><br><span class="line">懒汉模式 ConfigManagerIdler ------&gt;&gt;&gt;&gt; 创建</span><br><span class="line">username : root</span><br><span class="line">password : simon</span><br><span class="line"></span><br><span class="line">two  -----------------</span><br><span class="line">username : root</span><br><span class="line">password : simon</span><br><span class="line"></span><br><span class="line">username : root</span><br><span class="line">password : simon</span><br><span class="line"></span><br><span class="line">username : root</span><br><span class="line">password : simon</span><br></pre></td></tr></table></figure>

<p>控制台输出可以看到，三个工具类的通过单例模式可以保证系统中，应用该模式的类一个类只有一个实例。即一个类只有一个对象实例</p>
<h1 id="示例下载"><a href="#示例下载" class="headerlink" title="示例下载"></a><a target="_blank" rel="noopener" href="https://gitee.com/admin-james/Singleton">示例下载</a></h1>
    </div>

    
    
    

    <footer class="post-footer">
          <div class="reward-container">
  <div>请我一杯咖啡吧！</div>
  <button>
    赞赏
  </button>
  <div class="post-reward">
      <div>
        <img src="/images/wechatpay.jpg" alt="Jaron Chim 微信">
        <span>微信</span>
      </div>
      <div>
        <img src="/images/alipay.jpg" alt="Jaron Chim 支付宝">
        <span>支付宝</span>
      </div>

  </div>
</div>

          <div class="post-tags">
              <a href="/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" rel="tag"># 设计模式</a>
              <a href="/tags/%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F/" rel="tag"># 单例模式</a>
              <a href="/tags/%E9%A5%BF%E6%B1%89%E6%A8%A1%E5%BC%8F/" rel="tag"># 饿汉模式</a>
              <a href="/tags/%E6%87%92%E6%B1%89%E6%A8%A1%E5%BC%8F/" rel="tag"># 懒汉模式</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2018/04/05/MyBatis-%E6%98%A0%E5%B0%84%E9%85%8D%E7%BD%AE%E8%A7%A3%E6%9E%90%E4%BB%A5%E5%8F%8A%E5%8A%A8%E6%80%81SQL%E9%85%8D%E7%BD%AE%E6%A1%88%E4%BE%8B/" rel="prev" title="MyBatis 映射配置解析以及动态SQL配置案例">
                  <i class="fa fa-angle-left"></i> MyBatis 映射配置解析以及动态SQL配置案例
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2018/05/15/Struts2-%E4%B8%8E-Servlet-API-%E8%A7%A3%E8%80%A6-%E8%80%A6%E5%90%88%E7%9A%84%E8%AE%BF%E9%97%AE%E6%96%B9%E5%BC%8F/" rel="next" title="Struts2 与 Servlet API 解耦,耦合的访问方式">
                  Struts2 与 Servlet API 解耦,耦合的访问方式 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="beian"><a href="https://beian.miit.gov.cn/" rel="noopener" target="_blank">粤ICP备2025405034号-1 </a>
  </div>
  <div class="copyright">
    &copy; 2016 – 
    <span itemprop="copyrightYear">2025</span>
    <span class="with-love">
      <i class="fa fa-user"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">Jaron Chim</span>
  </div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>

</body>
</html>
